package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.schedule.dto.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.schedule.feign.ScheduleClient;
import com.heima.utils.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 霍森彪
 * @date 2022/7/22 16:21
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    @Async
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        task.setParameters(ProtostuffUtil.serialize(wmNews));

        scheduleClient.addTask(task);

        log.info("添加任务到延迟服务中----end");
    }


    @Autowired
    private AutoScanServiceImpl wmNewsAutoScanService;

    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() {
        ResponseResult responseResult = scheduleClient.poll();
        if (responseResult == null || responseResult.getCode() != 200) {
            log.warn("消费失败");
            return;
        }

        Object data =  responseResult.getData();
        if (data == null) {
            log.warn("没有可消费的任务");
            return;
        }

        String dataJson = JSON.toJSONString(data);
        if (StringUtils.isEmpty(dataJson)){
            log.warn("没有可消费的任务");
            return;
        }
        Task task = JSON.parseObject(dataJson, Task.class);
        if (task == null) {
            log.warn("没有可消费的任务");
            return;
        }

        byte[] parameters = task.getParameters();
        WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
        if (wmNews == null) {
            log.warn("参数缺失");
            return;
        }

        try {
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
